<?php

namespace catchAdmin\registration\excel;

use app\common\business\Follow as FollowBusiness;
use app\common\model\Follow as FollowModel;
use catchAdmin\permissions\model\Users as UsersModel;
use catcher\exceptions\FailedException;
use catcher\library\excel\ExcelContract;
use MongoDB\BSON\ObjectId;

class MyFollowExport implements ExcelContract
{
    /**
     * 设置头部
     *
     * @time 2020年09月08日
     * @return string[]
     */
    public function headers(): array
    {

        // TODO: Implement headers() method.
        return [
            '姓名','病案号','住院号','在院状态','性别','出生日期','民族','职业','证件号','联系电话','疾病诊断','生存状态','死亡日期','死亡原因','初治年龄','首次确诊日期','随访计划名称','随访人员','随访方式','随访状态','是否有效随访','随访时间','随访结果','紧急联系人','紧急联系人电话','入院科室','入院病区','主治医师工号','主治医师姓名','身体状况','不良反应','随访结论','复发检查时间','复发部位','转移检查时间','转移部位'
        ];
    }

    /**
     * 处理数据
     *
     * @time 2020年09月08日
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @return array
     */
    public function sheets(): array
    {
        $user = request()->user();
        $req = request()->param();

        //判断角色
        $roles = (new UsersModel())->currentUserRoleInfo($user['id'], 'role.identify')->column('identify');

        $where = [];
        if (!empty(array_intersect($roles, ['dsjzxsfry']))) {
            $where[] = ['follow_staff.user_id', '=', $user['id']];
        }

        if (isset($req['patientId']) && !empty($req['patientId'])) {
            $where[] = ['patientId', 'in', $req['patientId']];
        }

        //获取匹配条件的随访id
        $follow_ids = (new FollowModel())->mongoSearch([],[],['patientId'])
            ->where($where)
            ->order('_id', 'desc')
            ->column('id');

        $followIds = array_map(function ($followId) {
            return new ObjectId($followId);
        }, $follow_ids);

        if (!$followIds) {
            throw new FailedException('暂无数据，无需导出');
        }
        return (new FollowBusiness())->followTaskExportCondition($followIds);
    }

    public function setRow(): int
    {
        return 1;
    }
}